package com.charity.controller;

import com.charity.domain.Donation;
import com.charity.service.IDonationService;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/donation")
public class DonationController {

    @Resource
    private IDonationService donationService;

    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createDonation(@RequestBody Donation donation) {
        Map<String, Object> response = new HashMap<>();
        if (donationService.createDonation(donation)) {
            response.put("code", 200);
            response.put("message", "捐赠成功");
        } else {
            response.put("code", 400);
            response.put("message", "捐赠失败");
        }
        return ResponseEntity.ok(response);
    }

    @GetMapping("/detail/{donationId}")
    public ResponseEntity<Map<String, Object>> getDonationDetail(@PathVariable Long donationId) {
        Map<String, Object> response = new HashMap<>();
        Donation donation = donationService.getDonationById(donationId);
        if (donation != null) {
            response.put("code", 200);
            response.put("message", "获取成功");
            response.put("data", donation);
        } else {
            response.put("code", 404);
            response.put("message", "记录不存在");
        }
        return ResponseEntity.ok(response);
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getUserDonations(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        Map<String, Object> response = new HashMap<>();
        List<Donation> donations = donationService.getUserDonations(userId, pageNum, pageSize);
        double totalAmount = donationService.getUserTotalAmount(userId);
        response.put("code", 200);
        response.put("message", "获取成功");
        response.put("data", donations);
        response.put("totalAmount", totalAmount);
        return ResponseEntity.ok(response);
    }

    @GetMapping("/project/{projectId}")
    public ResponseEntity<Map<String, Object>> getProjectDonations(
            @PathVariable Long projectId,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        Map<String, Object> response = new HashMap<>();
        List<Donation> donations = donationService.getProjectDonations(projectId, pageNum, pageSize);
        double totalAmount = donationService.getProjectTotalAmount(projectId);
        response.put("code", 200);
        response.put("message", "获取成功");
        response.put("data", donations);
        response.put("totalAmount", totalAmount);
        return ResponseEntity.ok(response);
    }
}